package com.wen.ui;

import com.wen.bean.DigitalText;
import com.wen.bean.JIpAddressField;
import com.wen.util.ScanObject;
import com.wen.util.Scanner;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: wenxin
 * @Date: 2022/6/24 17:31
 * @Version: 1.0
 */
public class portScan {

    private JFrame frame;
    private JPanel rootPanel;
    private JPanel h;
    private JPanel c;
    private JPanel b;
    private JIpAddressField jIpAddressField;
    private JFormattedTextField port_start;
    private JFormattedTextField port_end;
    private JButton findButton;
    private JButton stopButton;
    private JTable table1;
    private DefaultTableModel tModel1;
    private JScrollPane scroll1;
    private Scanner scanner;
    private List<ScanObject> successObjects;
    private JLabel statusLable;



    private List<ScanObject> scanObjects;

    public portScan() {
        initComponent();
        bindButton();
        frame = new JFrame("端口扫描");
        frame.setContentPane(rootPanel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        // 窗口居中
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation((d.width - frame.getSize().width) / 2,
                (d.height - frame.getSize().height) / 2);
        frame.setIconImage(new ImageIcon("resource/icon/icon1.png").getImage());
    }

    /**
     * 初始化窗体组件
     */
    private void initComponent()
    {


        setTable1Data(new ArrayList<>());

        h.setLayout(new GridLayout());
        h.setBorder(new EmptyBorder(10,10,0,10));

        JPanel p1=new JPanel();
        final FlowLayout flowLayout = new FlowLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        flowLayout.setHgap(0);
        flowLayout.setVgap(0);
        p1.setLayout(flowLayout);


        p1.add(new JLabel("ip："));
        jIpAddressField=new JIpAddressField();
        p1.add(jIpAddressField);
        p1.add(new JLabel("起始端口："));
        port_start = new JFormattedTextField(NumberFormat.getIntegerInstance( ));
        Dimension digitalSize = new Dimension(50, 23);
        port_start.setPreferredSize(digitalSize);
        p1.add(port_start);

        p1.add(new Label(" -"));
        port_end = new JFormattedTextField(NumberFormat.getIntegerInstance( ));
        port_end.setPreferredSize(digitalSize);
        p1.add(port_end);
        h.add(p1);


        JPanel p2=new JPanel();
        final FlowLayout flowLayout2 = new FlowLayout();
        flowLayout2.setAlignment(FlowLayout.RIGHT);
        flowLayout2.setHgap(0);
        flowLayout2.setVgap(0);
        p2.setLayout(flowLayout2);
        findButton=new JButton("扫描");
        p2.add(findButton);
        stopButton=new JButton("停止");
        p2.add(stopButton);
        h.add(p2);


        EmptyBorder emptyBorder=new EmptyBorder(5,10,10,10);
        BorderLayout layout=new BorderLayout();
        c.setLayout(layout);
        c.setBorder(emptyBorder);
        scroll1 = new JScrollPane(table1);
        c.add(scroll1,BorderLayout.CENTER);

        b.setLayout(new BorderLayout());
        b.setBorder(emptyBorder);
        statusLable=new JLabel("未执行扫描");
        b.add(statusLable,BorderLayout.SOUTH);

    }
    public void listenerKeyNum(TextField jTextField){
        jTextField.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {

            }

            @Override
            public void keyPressed(KeyEvent e) {
                char c = e.getKeyChar();
                if (!(c >= '0' && c <= '9')) {
                    e.consume();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }
        });
    }


    private void bindButton(){
        //扫描开始
        findButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(scanner!=null&&scanner.getRun()){
                    System.out.println("【TEST】执行中");
                    return;
                }
                statusLable.setText("开始扫描！");
                String ip=jIpAddressField.getIpAddress();
                Integer portstart=Integer.valueOf(port_start.getText());
                Integer portend=Integer.valueOf(port_end.getText());
                scanner = new Scanner(ip,portstart+"-"+portend);
                scanner.start();
                //任务列表
                scanObjects = scanner.getScanObjectList();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //有未执行和执行中的数据
                        Long activityNum=0L;
                        while (scanner.getRun()){
                            activityNum=scanObjects.stream().filter(x->{
                                return x.getState()==0||x.getState()==1;
                            }).count();
                            successObjects = scanObjects.stream().filter(x -> {
                                return x.getState() != 0;
                            }).collect(Collectors.toList());
                            //System.out.println(activityNum);
                            statusLable.setText("扫描中，任务总数【"+scanObjects.size()+"】,剩余任务【"+activityNum+"】");
                            setTable1Data(successObjects);
                            try {
                                Thread.sleep(250);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            }
                        }
                        statusLable.setText("扫描完成，共扫描完成【"+(scanObjects.size()-activityNum)+"】个端口");
                    }
                }).start();
            }
        });

        //停止扫描
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(scanner!=null&&scanner.getRun()){
                    scanner.shutdownNow();
                }
            }
        });

    }

    private void setTable1Data(List<ScanObject> list){
        Object[][] data=new Object[list.size()][5];
        String openStr;
        String stateStr;
        for (int i=0;i<list.size();i++){
            ScanObject obj=list.get(i);
            data[i][0]=obj.getIp();
            data[i][1]=obj.getPort();
            if(obj.getOpen()==null){
                openStr="未知";
            }else if(obj.getOpen()){
                openStr="开放";
            }else {
                openStr="关闭";
            }
            data[i][2]=openStr;
            if(obj.getState()==1){
                stateStr="扫描中";
            }else if(obj.getState()==2){
                stateStr="扫描完成";
            }else if(obj.getState()==-1){
                stateStr="异常";
            }else {
                stateStr="未扫描";
            }
            data[i][3]=stateStr;
            data[i][4]=obj.getService();
            //data[i][4]=obj.getBanner();
        }
        setTable1Data(data);
    }

    private void setTable1Data(Object[][] data){
        String[] columnNames1 =
                { "IP", "端口", "开放状态", "扫描状态", "服务"};

        if(tModel1==null){
            tModel1=new DefaultTableModel(data,columnNames1);
            table1=new JTable(tModel1);
        }
        tModel1.setDataVector(data,columnNames1);
    }


}
